from flask import Flask, jsonify, request 
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from dotenv import load_dotenv
import os

# 加载环境变量
load_dotenv()

# 初始化 Flask 应用
app = Flask(__name__)

# 配置数据库连接
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URI')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')

# 初始化 SQLAlchemy
db = SQLAlchemy(app)

# 定义 User 模型， 继承db.Model
class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def __repr__(self):
        return f'<User {self.username}>'
    
    def to_dict(self):
        """将模型转换为字典，用于JSON序列化"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }

# 创建数据库表（仅在应用启动时执行一次）
with app.app_context():
    db.create_all()

# 健康检查接口
@app.route('/health', methods=['GET'])
def health_check(): 
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.utcnow().isoformat()
    }), 200  #接口返回一个tuple，第一个是response，第二个是http状态码
# 实际返回(Response对象, 200)
 
# 获取所有用户  
@app.route('/api/users', methods=['GET'])
def get_users():
    users = User.query.all() # 查询所有用户
    return jsonify([user.to_dict() for user in users]), 200

# 获取单个用户
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = User.query.get_or_404(user_id)
    return jsonify(user.to_dict()), 200
# 获取单个用户
@app.route('/api/users/<string:user_name>/<string:email>', methods=['GET'])
def get_username(user_name,email):
    print(user_name,email   )
    user = User.query.filter_by(username=user_name,email=email).first_or_404()
    return jsonify(user.to_dict()), 200

# 创建新用户
@app.route('/api/users', methods=['POST'])
def create_user():
    data = request.get_json()
    
    # not data 检查请求体是否为空
    # not 'username' in data 检查请求体中是否包含username字段
    if not data or not 'username' in data or not 'email' in data:
        return jsonify({'error': 'Missing required fields (username or email)'}), 400
    
    # 检查用户名和邮箱是否已存在
    if User.query.filter_by(username=data['username']).first():
        return jsonify({'error': 'Username already exists'}), 409
    
    if User.query.filter_by(email=data['email']).first():
        return jsonify({'error': 'Email already exists'}), 409
    
    # 创建新用户
    new_user = User(
        username=data['username'],
        email=data['email']
    )
    
    # 保存到数据库
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify(new_user.to_dict()), 201

# 更新用户
@app.route('/api/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
    user = User.query.get_or_404(user_id)
    data = request.get_json()
    
    # 更新用户信息
    if 'username' in data:
        # 检查新用户名是否已被其他用户使用
        existing_user = User.query.filter_by(username=data['username']).first()
        if existing_user and existing_user.id != user_id:
            return jsonify({'error': 'Username already exists'}), 409
        user.username = data['username']
    
    if 'email' in data:
        # 检查新邮箱是否已被其他用户使用
        existing_user = User.query.filter_by(email=data['email']).first()
        if existing_user and existing_user.id != user_id:
            return jsonify({'error': 'Email already exists'}), 409
        user.email = data['email']
    
    # 保存更新
    db.session.commit()
    
    return jsonify(user.to_dict()), 200

# 删除用户
@app.route('/api/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    
    db.session.delete(user)
    db.session.commit()
    
    return jsonify({'message': f'User {user_id} has been deleted successfully'}), 200

# 错误处理
@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Resource not found'}), 404

@app.errorhandler(500)
def server_error(error):
    return jsonify({'error': 'Internal server error'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
    